package com.example.login.servlets;

import com.example.login.model.User;
import com.example.login.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
@WebServlet(urlPatterns = "/login")
public class LoginServlets extends HttpServlet {
    Connection connection=null;
    PreparedStatement preparedStatement=null;
    ResultSet resultSet=null;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String userName = req.getParameter("userName");
        String password =req.getParameter("password");
        String checkCode = req.getParameter("checkCode");

        try {
            connection = DBUtil.getConnection();
            String sql="select id,user_name,password from sys_user";
            preparedStatement= connection.prepareStatement(sql);
            resultSet=preparedStatement.executeQuery();
            List<User> userList=new ArrayList<>();
            while(resultSet.next()){
                int id=resultSet.getInt("id");
                String name=resultSet.getString("user_name");
                String pw=resultSet.getString("password");
                User user=new User(id,name,pw);
                userList.add(user);
            }
            HttpSession session = req.getSession();
            String checkCode_session = (String) session
                    .getAttribute("checkCode_session");
            // 删除session中存储的验证码
            session.removeAttribute("checkCode_session");

            for (User user:userList) {
                if (user.getUserName().equals(userName)&&user.getPassword().equals(password)){
                    req.getServletContext().setAttribute("userList",userList);
                    resp.sendRedirect("list.jsp");
                }
            }
            resp.sendRedirect("login.jsp");

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(preparedStatement!=null){
                    preparedStatement.close();
                }
                if (resultSet!=null){
                    resultSet.close();
                }
                if(connection!=null){
                    connection.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

